package com.java.springcloud.config;

import com.java.springcloud.util.ZkClient;
import org.apache.curator.RetryPolicy;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.retry.RetryNTimes;
import org.apache.curator.framework.CuratorFramework;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.apache.curator.framework.CuratorFrameworkFactory;

/**
 * @author dushougudu
 */
@Configuration
public class ZookeeperConfig {

    @Bean(initMethod = "start", destroyMethod = "close")
    public CuratorFramework curatorFramework(ZookeeperProperties zookeeperProperties) {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(zookeeperProperties.getElapsedTimeMs(),
                zookeeperProperties.getRetryCount());
        CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
                .connectString(zookeeperProperties.getAddress()).retryPolicy(retryPolicy)
                .sessionTimeoutMs(zookeeperProperties.getSessionTimeoutMs())
                .connectionTimeoutMs(zookeeperProperties.getConnectionTimeoutMs());
        return builder.build();
    }

    @Bean
    ZkClient zkClient(CuratorFramework curatorFramework) {
        return new ZkClient(curatorFramework);
    }

}